package com.bzxgc.sgwer.controller.dept;

import com.bzxgc.sgwer.common.page.Constant;
import com.bzxgc.sgwer.common.util.JsonResult;
import com.bzxgc.sgwer.common.util.PageData;
import com.bzxgc.sgwer.entity.dept.Dept;
import com.bzxgc.sgwer.service.dept.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping("/dept")
public class DeptController {

    @Autowired
    private DeptService deptService;

    @RequestMapping("/add")
    public String add() {
        return "dept/save";
    }

    @RequestMapping("/update/{id}")
    public String update(@PathVariable("id") Long id, HttpServletRequest request) {
        Dept dept = deptService.getDeptById(id);
        request.setAttribute("dept", dept);
        return "dept/save";
    }

    @RequestMapping("/ajax/save")
    @ResponseBody
    public JsonResult ajaxSave(Dept dept) {
        if (dept.getId() == null) {
            deptService.addDept(dept);
        } else {
            deptService.updateDept(dept);
        }
        return JsonResult.success("保存成功");
    }

    @RequestMapping("/ajax/delete")
    @ResponseBody
    public JsonResult ajaxDelete(@RequestParam("ids") Long[] ids) {
        deptService.updateDeptStatus(ids, 2);
        return JsonResult.success("删除成功");
    }

    @RequestMapping("/list")
    public String list(HttpServletRequest request) {
        int pageNum = Constant.DEFAULT_PAGE_NUM;
        String pageNumStr = request.getParameter("pageNum");
        if (pageNumStr != null && !pageNumStr.equals("")) {
            pageNum = Integer.parseInt(pageNumStr); // 显示第几页数据
        }

        int pageSize = Constant.DEFAULT_PAGE_SIZE;
        String pageSizeStr = request.getParameter("pageSize");
        if (pageSizeStr != null && !pageSizeStr.equals("")) {
            pageSize = Integer.parseInt(pageSizeStr); // 每页显示多少条记录
        }

        String name = request.getParameter("name");
        PageData<Dept> pageData = deptService.getDeptListByPage(pageNum, pageSize, name);
        request.setAttribute("pageData", pageData);
        request.setAttribute("name", name);
        request.setAttribute("pageNum", pageNum);
        return "dept/list";
    }
}
